<template> 
	<el-card>
		<template #header>   
				<el-input v-model="nodeFilterText" placeholder="过滤" >	
				<template #append>
					<el-tooltip content="一级目录为模块，不属于菜单,在菜单上右键可以导入、新增、修改、删除、菜单">
								<Icon icon="ep:warning"/> 
					</el-tooltip> 
				</template>		
			</el-input> 
		</template>
		<el-tree  v-adaptive
			class="filter-tree" accordion
			:data="treeData"
			:props="defaultTreeProps"
			:filter-node-method="filterNode"
			:show-checkbox="showCheckbox"
			:default-expand-all="defaultExpandAll"
			:expand-on-click-node="expandOnClickNode"
			:indent="indent"
			node-key="id"
			:default-expanded-keys="defaultExpandedKeys"
				:default-checked-keys="defaultCheckedKeys"
				auto-expand-parent
			@check-change="handleCheckChange"
			@current-change="handleCurrentChange"
			@node-click="handleNodeClick"  
			:check-strictly="checkStrictly" 
			:check-on-click-node="true"
			ref="nodeTree" @contextmenu.prevent>
			<template  #default="{ node, data}">
				<div class="custom-tree-node" @contextmenu.prevent title="右键可以增删改">
					<el-popover
						:open-delay="1000"
						placement="top-start" 
						:width="400"
						trigger="contextmenu" > 
						
						<el-button @click="openUpload(data)" icon="upload" title="只能导入到一级模块下">导入</el-button>
						<el-button  type="primary"   v-if="!data.isModule"
          @click="$refs['FormDialog'].open({ parentOpType: currOpType, subOpType: 'edit', formData: data,pnode:node })" icon="edit" title="修改一条数据"/>
					<el-button v-if="data.isModule" type="success" @click="showTopAdd(data,node)" icon="plus" title="新增一级菜单"  />
        <el-button v-if="!data.isModule" type="success" @click="showSubAdd(data,node)" icon="plus" title="新增子菜单"  />
				<el-button  type="warning" @click="getTreeData()" icon="refresh" title="刷新整个菜单"  />
        <el-button v-if="data.menuType == '1'" @click="$refs['menuButtonsDialog'].open({ pmenu: data })"
          icon="right" title="按钮"  /> 
					<el-popconfirm title="Are you sure to delete this?" @confirm="delMenuDef(data)">
						<template #reference>
							<el-button :disabled="data.isModule"
            type="danger"  icon="delete" />
						</template>
					</el-popconfirm>
          
						<template #reference><div style="display:flex;align-items:center;width:100%;"><Icon v-if="data.imageUrls" :icon="data.imageUrls"/>{{`${data.name||data.mname}(${data.children?.length||0})`}}</div></template>
					</el-popover> 
				</div> 
			</template>
		</el-tree>
	</el-card> 
	
  <!--新增修改明细 MenuDef 前端功能菜单表界面-->
  <mdp-dialog ref="FormDialog">
    <template #default="{ visible, data,dialog }">
      <menu-def-form :ref="refId + 'Form'" :visible="visible" :parent-op-type="data.currOpType" :sub-op-type="data.subOpType"
        :form-data="data.formData" @close="dialog.close()" @submit="(d)=>afterFormSubmit(d.data,data.subOpType,data.pnode)" @fieldsChange="(res,isOk,params,row)=>onEditChange(row,data.formData)"/>
    </template>
  </mdp-dialog>
  <!--新增导入按钮-->
  <mdp-dialog ref="menuButtonsDialog" title="按钮管理" width="70%">
    <template #default="{ visible, data, dialog }">
      <menu-buttons :pmenu="data.pmenu" :visible="visible" @close="dialog.close()" @submit="afterBtnSubmit" />
    </template>
  </mdp-dialog>

  <!--导入界面-->
  <mdp-dialog ref="importDialog" title="导入菜单"   max-height="100%">
    <template #default="{ visible, data, dialog }">
      <menu-def-import :module="data.module" :visible="visible" @close="dialog.close()" @submit="afterImportSubmit" />
    </template>
  </mdp-dialog>
</template>

<script>  
	import treeTool from '@/components/mdp-ui/js/treeTool'; 
	import { mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user'   

import {delMenuDef} from '@/api/mdp_pub/menuDef.js';
import MenuDefForm from './Form.vue';//新增修改明细界面 
import MenuButtons from './MenuButtons.vue'
import MenuDefImport from './MenuDefImport.vue'

	export default {
		components:{
			MenuDefForm,MenuButtons,MenuDefImport
		},
	    computed: {
		    ...mapState(useUserStore,[
		      'userInfo'
		    ])
		},
		watch: {
	      nodeFilterText(val) {
	        this.$refs.nodeTree.filter(val);
	      },
	      checkedKeys(val){
	      	 this.$refs.nodeTree.setCheckedKeys(val);
	      },
	      refresh(val){ 
	      	this.getTreeData(val);
	      },
	      currentKey(val){ 
	    	  this.$refs.nodeTree.setCheckedKeys([val]);
		  },
		  value(val){
		  	this.nodeid=val;
		  },
		  nodeid(val){
		  	this.$emit('input',val);
		  }
	    },
	    computed:{
	    	defaultExpandedKeys(){
	    		return this.defaultCheckedKeys;
	    	},
	    	defaultCheckedKeys(){
	    		if(this.value){
	    			return [this.value];
	    		}
	    		return this.checkedKeys;
	    	},
	    	nodeKey_(){
	    		return this.nodeKey?this.nodeKey:'id'
	    	},
			treeData(){
				var treeData= treeTool.translateDataToTree(this.menuDefs,'pid','id'); 
				var modules=JSON.parse(JSON.stringify(this.menuModules))
				modules.forEach(k=>k.isModule=true)
				var defModule={id:'un-set-module',pid:'Mo',mname:'未分配模块',children:[],moduleId:'un-set-module',isModule:true}
				modules.forEach(i=>{
					i.moduleId=i.id
					i.isModule=true
				})
				treeData.forEach(m=>{ 
					var module=modules.find(mo=>m.moduleId==mo.id)
					if(!module){
						defModule.children.push(m)
					}else{
						module.children.push(m)
					}

				})
				if(defModule.children.length>0){
					modules.push(defModule)
				}
				return modules;
			}
	    },
	    props: ['checkStrictly','disabledRule','value','visible','nodeKey','showCount','countTips','showFilter','rootKey','multiple','checkedKeys','refresh','defaultExpandAll','expandOnClickNode','showCheckbox','indent'],
		data() {
			return { 
				nodeFilterText: '',
				menuDefs:[], 
				defaultTreeProps:{
					
					id:this.nodeKey?this.nodeKey:'id',
					label:'mname',
					children: 'children',
					disabled: 'disabled'
				},  
				listLoading: false,
				nodeid:'',
				menuModules:[],
			}
		},
		methods: { 
			delMenuDef(d){
				delMenuDef(d).then((res)=>{
					if(res.tips.isOk){  
						this.$refs['nodeTree'].remove(d)
						this.$message.sucess(res.tips.msg)
					}else{ 
						this.$message.sucess(res.tips.msg)
					}
				})
			},
			onEditChange(d,treeData){  
				debugger
				//这个不起作用
				//this.$refs['nodeTree'].updateKeyChildren(d.id,d)
				Object.assign(treeData,d)
			},
			afterFormSubmit(d,subOpType,pnode){
				debugger
				if(subOpType=='add'){ 
					this.$refs['nodeTree'].append(d,pnode)
				}
			},
			afterBtnSubmit(){
				this.getTreeData()
			},
			afterImportSubmit(){
				this.getTreeData()
			},
		handleCheckChange(data, checked, indeterminate) {
			let checkedKeys = this.$refs.nodeTree.getCheckedKeys();

			if (this.multiple === undefined || this.multiple === false || this.multiple === 'false') {
				if (checked == true) {
					if (checkedKeys.length > 1) {
						this.$refs.nodeTree.setCheckedKeys([data['id']]);
						this.$emit('check-change', data, checked, indeterminate);
						this.nodeid = data['id'];
					} else {
						this.$emit('check-change', data, checked, indeterminate);
						this.nodeid = data['id'];
					}
				} else {
					if (checkedKeys.length == 0) {
						this.nodeid = '';
						this.$emit('check-change', data, checked, indeterminate);
					}
				}
			} else {
				this.$emit('check-change', data, checked, indeterminate);
			}
		},
			handleCurrentChange(data, node) {
		    	this.$emit('current-change',data, node); 
		    },
		    handleNodeClick(data, node, comp) { 
				this.$emit('node-click',data, node, comp); 
		    },
			openUpload(module){
				if(!module.isModule){
					this.$message.error('只能导入一级模块，请选中一级模块')
					return
				}
				this.$refs['importDialog'].open({module:module})
			},
		     
			//获取分类树列表
			getTreeData(refresh) {

				let id='';
				if(this.rootKey!='' && this.rootKey!=null){
					id=this.rootKey;
				}
				let params = { 
					id: id
				};
 				if(refresh){
 					params.refresh=true;
 				}
				this.listLoading = true;
				this.$mdp.listMenuTree(params).then((res) => {
					var tips=res.tips;
					if(tips.isOk==true){  
						this.menuDefs=res.data
						if(this.disabledRule){
							this.menuDefs.forEach(m=>this.disabledRule(m))
						}
						
					}else{
						this.$message({ message: tips.msg, type: 'error'});
					} 
					this.listLoading = false;
				}).catch(() => {
					this.listLoading = false;
				});
			}, 
			filterNode(value, data) {
		        if (!value) return true;
						if(data.name){
							return data.name.indexOf(value) !== -1;
						}else if(data.mname) {
							return data.mname.indexOf(value) !== -1;
						}else{
							return false;
						}
		        
		     },
		     renderContent(h, { node, data, store }) {
		    	 var countMsg='';	
		    	 if(this.countTips){
	    	 			countMsg=this.countTips;
	    	 		}
		    	 	if(this.showCount==true || this.showCount=='true'){
		    	 		let msg="";
		    	 		if(data.menuType=='2'){
		    	 			msg='-按钮';
		    	 			return h('span',{},[node.label,h('font',{style:{color:'red'}}, msg)]) ;
		    	 		}else{
		    	 			msg="("+ data.count +countMsg+")"; 
		    	 			return h('span',{},[node.label,h('font',{style:{color:'blue'}},msg )]) ;
		    	 		} 
		    	 	}else{
		    	 		let msg="";
		    	 		if(data.menuType=='2'){ 
		    	 			msg='-按钮';
		    	 			return h('span',{},[node.label,h('font',{style:{color:'red'}}, msg)]) ;
		    	 		}else{
		    	 			msg="("+(data.children==null?0:data.children.length)+countMsg+")"
		    	 			return h('span',{},[node.label,h('font',{style:{color:'blue'}},msg )]) ;
		    	 		}
		    	 		
		    	 	}
			        
			  },
				
				showTopAdd(row,pnode) {
					var formData = {}
					formData.pid = 'M0'
					formData.pMname = row.name
					formData.moduleId=row.moduleId
					this.$refs["FormDialog"].open({ subOpType: 'add', formData: formData,pnode:pnode })
				},
				showSubAdd(row,pnode) {
					var formData = {}
					formData.pid = row.id
					formData.pMname = row.mname
					formData.moduleId=row.moduleId
					this.$refs["FormDialog"].open({ subOpType: 'add', formData: formData,pnode:pnode })
				},
		},
		mounted() { 
			
			this.$mdp.listMenuModule({}).then(res=>{
				var menuModules=res.data
				this.menuModules=menuModules.map(k=>{
					k.pid='M0'
					k.mname=k.name
					k.children=[]
					return k;
				})
			});
			this.nodeid=this.value;
			this.getTreeData(); 
		}
	}

</script>

<style scoped>

</style>